<template>
  <div id="userLoginView">
    <h2 style="margin-bottom: 16px">用户登录</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      :model="form"
      label-align="left"
      auto-label-width
      @submit="handleSubmit"
    >
      <a-form-item field="userAccount" label="账号">
        <a-input v-model="form.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item field="userPassword" tooltip="密码不少于八位" label="密码">
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item
        field="code"
        label="code"
        :rules="[
          { required: true, message: '需要验证码' },
          { minLength: 6, message: '验证码不完整' },
          { match: /^[a-zA-Z0-9]+$/, message: '必须是数字或字母' },
        ]"
      >
        <a-verification-code v-model="form.codeCaptcha" style="width: 300px" />
        <div>
          <img
            :src="'data:image/png;base64,' + captcha"
            alt=""
            v-on:click="getCodeBase64"
          />
        </div>
      </a-form-item>
      <a-form-item>
        <a-button html-type="submit" style="width: 120px" type="primary"
          >登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { UserControllerService, UserLoginRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const form = reactive({
  userAccount: "",
  userPassword: "",
  codeCaptcha: "",
} as UserLoginRequest);
//验证码
const captcha = ref();
const router = useRouter();
const store = useStore();
const handleSubmit = async () => {
  const res = await UserControllerService.userLoginUsingPost(form);
  //登录成功跳转到主页
  if (res.code === 200) {
    await store.dispatch("user/getLoginUser");
    router.push({
      path: "/",
      replace: true,
    });
  } else {
    message.error("登陆失败," + res.message);
    getCodeBase64();
  }
};
const getCodeBase64 = async () => {
  const res = await UserControllerService.getNewCaptchaUsingGet();
  if (res.code === 200) {
    captcha.value = res.data as string;
  } else {
    message.error("获取验证码失败");
  }
};
//页面加载获取验证码
onMounted(() => {
  getCodeBase64();
});
</script>

<style scoped>
#userLoginView {
}

img {
  margin-left: 25px;
  width: 130px;
}
</style>
